package com.app.business.service;

import com.app.business.model.House;
import com.app.business.model.HousePersonForProperty;
import com.app.business.utils.PropertyPersonUtils;
import com.app.system.jpa.JpaBaseDao;
import com.app.system.jpa.PageBean;
import com.app.system.jpa.Wrapper;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.WebUtils;
import com.app.system.utils.exception.AjaxException;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.google.common.collect.Maps;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ddz on 2020/9/1.
 */
@SuppressWarnings(value = "ALL")
@Service
@Transactional
public class HousePersonForPropertyService extends JpaBaseDao<HousePersonForProperty, Integer> {

    @Autowired
    private HouseService houseService;
    @Autowired
    private ActionHistoryService actionHistoryService;
    @Autowired
    private ReduceRecordsService reduceRecordsService;

    /**
     * 根据房源Id得到减免人列表
     *
     * @param contractId
     * @return
     */
    public List<HousePersonForProperty> getHousePersonListByHouseId(Integer houseId) {
        //查询语句
        String hql = " from HousePersonForProperty hpp where hpp.house.id = :houseId order by hpp.id";
        Map<String, Object> map = new HashMap<>();
        map.put("houseId", houseId);
        return this.findHql(hql, map);
    }

    /**
     * 分页处理根据房源id获取
     *
     * @return
     */
    public PageBean<HousePersonForProperty> housePersonForPropertyPageBeanByHouseId(Integer houseId) {
        //查询语句
        StringBuffer query = new StringBuffer(" hp from HousePersonForProperty hp inner join fetch hp.house h ");

        //默认排序(PageBean指定排序字段类型的话，则默认排序不使用)
        StringBuffer orderBy = new StringBuffer(" hp.id ");
        Wrapper wrapper = new Wrapper(query, orderBy);
        wrapper.andEq("h.id", houseId);
        wrapper.initSearchParams();
        return this.pageHql(wrapper);
    }

    /**
     * 根据身份证号得到该减免人
     *
     * @param contractId
     * @return
     */
    public List<HousePersonForProperty> getHousePersonListByIdCard(String idCard) {
        //查询语句
        String hql = " from HousePersonForProperty hpp inner join fetch hpp.house h where hpp.idCard = :idCard order by hpp.id";
        Map<String, Object> map = new HashMap<>();
        map.put("idCard", idCard);
        return this.findHql(hql, map);
    }

    /**
     * 产权人身份证号验证查重
     *
     * @param contractId
     * @param zsProjectId
     * @param chooseHouseNum
     * @return
     */
    public String validateIdCard(Integer houseId, String freeArea, String idCard) {
        StringBuffer hql = new StringBuffer(" select * from house_person_for_property where id != :buyHousePersonId and contract_id =:contractId and id_card =:idCard ");
        Map<String, Object> map = Maps.newLinkedHashMap();
        map.put("idCard", idCard);

        List list = this.findSqlObject(hql.toString(), map);
        if (CollectionUtils.isNotEmpty(list)) {
            return "该身份证号已存在";
        }
        return null;

    }


    /**
     * 删除某房源下所有的减免人员数据
     *
     * @param houseId
     */
    public synchronized void deleteHousePersonForPropertyByHouseId(Integer houseId) {
        String sql = "delete from house_person_for_property where house_id = :houseId";
        this.entityManager.createNativeQuery(sql).setParameter("houseId", houseId).executeUpdate();
    }


    /**
     * 得到房源id和当前房源的List<HousePersonForProperty>对应的map
     *
     * @param buyHousePersonList
     * @return
     */
    public Map<String, List<Map>> getHousePersonForPropertyByHouse() {
        List<Map> valueList = null;
        StringBuffer sql = new StringBuffer(" SELECT * FROM house_person_for_property bbp, ");
        sql.append(" (SELECT h.id AS houseId FROM house h) ha ");
        sql.append(" WHERE bbp.house_id=ha.houseId");
        Query query = this.entityManager.createNativeQuery(sql.toString());
        List<Map> housePersonForPropertyList = query.unwrap(org.hibernate.SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        Map<String, List<Map>> map = Maps.newLinkedHashMap();
        if (CollectionUtils.isNotEmpty(housePersonForPropertyList)) {
            for (Map map1 : housePersonForPropertyList) {
                String houseId = String.valueOf(map1.get("houseId"));
                valueList = map.get(houseId) == null ? new ArrayList<>() : map.get(houseId);
                valueList.add(map1);
                map.put(houseId, valueList);
            }
        }
        return map;
    }


    /**
     * 根据房源id得到减免人列表MAp
     *
     * @param houseId
     * @return
     */
    public Map<String, String> getHousePersonForPropertyListByHouseId() {
        StringBuffer sql = new StringBuffer(" SELECT hp.house_id AS 'houseId',GROUP_CONCAT(hp.name) AS 'nameStr' ");
        sql.append("  FROM house_person_for_property hp ");
        sql.append("  GROUP BY hp.house_id");
        List<Map> housePersonForPropertyNameStrList = this.findSql(sql.toString(), null);
        Map<String, String> resultMap = Maps.newLinkedHashMap();
        if (CollectionUtils.isNotEmpty(housePersonForPropertyNameStrList)) {
            for (Map map1 : housePersonForPropertyNameStrList) {
                String houseId = map1.get("houseId").toString();
                String HousePersonForPropertyName = map1.get("nameStr").toString();
                resultMap.put(houseId, HousePersonForPropertyName);
            }
        }
        return resultMap;
    }

    /**
     * 减免基础数据保存
     *
     * @param request
     * @return
     */
    @Transactional
    public synchronized Response housePersonForPropertySave(HttpServletRequest request) throws AjaxException {
        Integer houseId = ParamUtils.getInt(request, "houseId", 0);
        House house = this.houseService.findOne(houseId);
        Integer housePersonForPropertyId = ParamUtils.getInt(request, "housePersonForPropertyId", 0);
        HousePersonForProperty housePersonForProperty = this.findOne(housePersonForPropertyId);
        housePersonForProperty = housePersonForProperty == null ? new HousePersonForProperty() : housePersonForProperty;

        Precondition.checkSqdsArguement(housePersonForProperty != null, "数据错误！");
        Precondition.checkSqdsArguement(house != null, "房源不存在！");
        WebUtils.bind(request, housePersonForProperty);
        housePersonForProperty.setHouse(house);


        this.save(housePersonForProperty);
        this.actionHistoryService.saveActionHistoryByContractId(housePersonForProperty.getHouse().getContract().getId(),
                "设置房号为" + housePersonForProperty.getHouse().getHouseNumStr() + "的减免人ID为：" + housePersonForProperty.getName(), "设置物业减免人");
        Response response = PropertyPersonUtils.getPropertyPersonLimit(housePersonForProperty);

        //计算单人物业减免费用
        this.reduceRecordsService.cal(housePersonForProperty);//计算物业减免费用

        //批量计算物业费减免办法
        /*List<HousePersonForProperty> propertyList = this.getListByAzProjectId(3);
        if (CollectionUtils.isNotEmpty(propertyList)) {
            for (HousePersonForProperty housePersonForProperty1 : propertyList) {
                this.reduceRecordsService.cal(housePersonForProperty1);//计算物业减免费用
            }
        }*/
        Precondition.checkAjaxArguement(response.getCode().equals("0001"), "1111", response.getMessage());
        return new Response("0001", "保存成功");
    }


    /**
     *
     * @return
     */
    public Map<String, List<HousePersonForProperty>> getHousePersonForPropertyByAzProjectId() {
        //查询语句
        StringBuffer sql = new StringBuffer("select * from house_person_for_property hp inner join house h on hp.house_id=h.id ");
        List<Map> mapList = this.entityManager.createNativeQuery(sql.toString())
                .unwrap(org.hibernate.SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();

        Map<String, List<HousePersonForProperty>> azProjectMap = Maps.newLinkedHashMap();
        if (CollectionUtils.isNotEmpty(mapList)) {
            for (Map map : mapList) {
                String azProjectId = String.valueOf(map.get("h.az_project_id"));

                List<HousePersonForProperty> housePersonForPropertyList = azProjectMap.get(azProjectId) == null ? new ArrayList() : azProjectMap.get(azProjectId);
                housePersonForPropertyList.add((HousePersonForProperty) map);
                azProjectMap.put(azProjectId, housePersonForPropertyList);
            }
        }
        return azProjectMap;
    }


    public List<HousePersonForProperty> getListByAzProjectId(Integer azProjectId) {
        StringBuffer hql = new StringBuffer(" from HousePersonForProperty h where h.house.azProject.id = :azProjectId ");
        Map<String, Object> map = new HashMap<>();
        map.put("azProjectId", azProjectId);
        return this.findHql(hql.toString(), map);
    }

}
